import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    num: 1,
    goods: JSON.parse(localStorage.cart || '[]')
  },
  mutations: {
    addCar(state, obj) {
      let flag = false
      state.goods.forEach(el => {
        if (el.id === obj.goodsCar.id) {
          el.num += obj.goodsCar.num
          flag = !flag
        }
      })
      if (!flag) {
        state.goods.push(obj.goodsCar)
      }
      localStorage.cart = JSON.stringify(state.goods)
    }
  },
  getters: {
    getallGoods(state) {
      let num = 0
      state.goods.forEach(el => {
        num += el.num
      })
      return num
    },
    getallPrice(state) {
      let price = 0
      let flag1 = false
      state.goods.forEach(el => {
        if (el.select) {
          price += el.num * el.price
          flag1 = !flag1
        }
      })
      return price
    },
    getall(state) {
      let flag1 = false
      const o = state.goods.every(el => {
        return el.select
      })
      if (o) {
        flag1 = true
      } else {
        flag1 = false
      }
      return flag1
    }
  },
  actions: {
  },
  modules: {
  }
})
